import axios from "axios";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useLocalStore } from "@/pinia/local";
import { I18nPackage } from "@/types";
import { store } from "./index";

const KEY = "language";

/**
 * 多语言
 */
export const useLanguageStore = defineStore(KEY, () => {
  const placeholder = "{}"; // 占位符
  const language = computed(() => useLocalStore().getLanguage() as string);
  const mapping = ref(
    getDB().getItem(KEY)
      ? (JSON.parse(getDB().getItem(KEY)!) as I18nPackage)
      : null
  );

  function load() {
    try {
      const { loadingStore } = store();
      loadingStore.loading("加载国际化配置...");
      if (!mapping.value) {
        axios.get("/i18n.json?t=" + new Date().getTime()).then((res: any) => {
          const { data } = res;
          mapping.value = data;
          getDB().setItem(KEY, JSON.stringify(mapping.value));
        });
      }
    } catch (ex) {
      return Promise.reject("加载多语言失败");
    }
  }

  function get(key: string, ...params: (string | number)[]) {
    return getByLanguage(key, language.value, ...params);
  }

  function getByLanguage(
    key: string,
    customLanguage: string,
    ...params: (string | number)[]
  ) {
    let realKey = key
      .split(/\./)
      .map((item) => `['${item}']`)
      .join("");
    let content = eval(`mapping.value['${customLanguage}']${realKey}`);
    if (params.length > 0) {
      params.forEach((param) => {
        content = content.replace(placeholder, param);
      });
    }
    return content;
  }

  function getDB() {
    return sessionStorage;
  }

  function clear() {
    getDB().removeItem(KEY);
  }

  return { load, get, getByLanguage, clear };
});
